package tcc.ctrl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import tcc.dao.UsuarioDAO;
import tcc.model.Usuario;
import tcc.util.Site;

@WebServlet(urlPatterns = { "/perfil" })
public class Perfil extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String data = "";
		int dia = 1;
		int mes = 1;
		int ano = 2013;

		Usuario usuario = (Usuario) req.getSession().getAttribute("usuario");

		// se o usuario não estiver logado, envia para login
		if (usuario == null) {
			req.setAttribute("content", "login.jsp");
			req.getRequestDispatcher("/template.jsp").forward(req, resp);
			return;
		}

		if (usuario.getData_nasc() == null) {
			data = "Ainda não fornecida";
		} else {
			data = new SimpleDateFormat("DD/MM/YYYY").format(usuario
					.getData_nasc());
			dia = Integer.parseInt(new SimpleDateFormat("DD").format(usuario
					.getData_nasc()));
			mes = Integer.parseInt(new SimpleDateFormat("MM").format(usuario
					.getData_nasc()));
			ano = Integer.parseInt(new SimpleDateFormat("YYYY").format(usuario
					.getData_nasc()));
		}

		req.setAttribute("data", data);
		req.setAttribute("dia", dia);
		req.setAttribute("mes", mes);
		req.setAttribute("ano", ano);

		req.setAttribute("content", "perfil.jsp");
		req.getRequestDispatcher("/template.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.setCharacterEncoding("UTF-8");
		System.out.println(req.getClass().getName());

		try {
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(req);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input
					// type="text|radio|checkbox|etc", select, etc).
					String fieldname = item.getFieldName();

					// passa a string para UTF8
					String fieldvalue = new String(item.getString().getBytes(
							"latin1"), "UTF-8");

					req.setAttribute(fieldname, fieldvalue);
				} else {
					// Process form file field (input type="file").
					String fieldname = item.getFieldName();
					String filename = FilenameUtils.getName(item.getName());
					InputStream filecontent = item.getInputStream();
					req.setAttribute(fieldname, filename);
					req.setAttribute(fieldname + "InputStream", filecontent);
				}
			}

			Usuario u = (Usuario) req.getSession().getAttribute("usuario");
			u.setNome((String) req.getAttribute("nome"));
			u.setNick((String) req.getAttribute("nick"));

			// trabalhando datas.
			int dia = Integer.parseInt((String) req.getAttribute("dateDia"));
			int mes = Integer.parseInt((String) req.getAttribute("dateMes"));
			int ano = Integer.parseInt((String) req.getAttribute("dateAno"));

			Calendar cal = Calendar.getInstance();
			// janeiro = 0... dezembro = 11
			cal.set(ano, mes - 1, dia);
			u.setData_nasc(cal.getTime());

			UsuarioDAO uDAO = new UsuarioDAO();
			uDAO.atualizar(u); // atualizando

			if (req.getSession().getAttribute("file") != null) {
				// continuar daqui, esta dando erro na hora de commitar as
				// mudnaças, algum valor esta setado como null não sei qual é;
			}

			// ... (do your job here)
			/*
			 * System.out.println(fieldname + ": " + filename);
			 * 
			 * OutputStream out = new FileOutputStream(new File(
			 * Site.URLimagePATH + filename)); IOUtils.copy(filecontent, out);
			 * System.out.println(getServletContext().getRealPath( "roberto"));
			 */

			resp.sendRedirect("./perfil");

		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		}

	}
}
